/**
 * @(#)ApkConfigController.java 2017年03月1日
 * Copyright(C) 2017 ZHEXIN IT CO.,LTD. All rights reserved.
 */
package org.jsbd.boss.action;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.jsbd.boss.domian.ChannelProvinceInfo;
import org.jsbd.boss.domian.MiguMusicConfigBean;
import org.jsbd.boss.domian.MiguVideoConfigBean;
import org.jsbd.boss.domian.MiguVideoProvinceConfig;
import org.jsbd.boss.domian.ProvinceInfo;
import org.jsbd.boss.domian.channel.FileUploadVo;
import org.jsbd.boss.service.FileManager;
import org.jsbd.boss.service.IIpService;
import org.jsbd.boss.service.IMiguMusicConfigService;
import org.jsbd.boss.service.IMiguVideoConfigService;
import org.jsbd.boss.util.ReadMGVideoPkg;
import org.jsbd.boss.annotation.SystemControllerLog;
import org.jsbd.boss.common.DataGridModel;
import org.jsbd.boss.common.ResponseMapUtils;
import org.jsbd.boss.common.ResponseUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;


@Controller
@RequestMapping("/miguVideoConfig")
public class MiguVideoConfigController{

	private static final Logger LOGGER=LoggerFactory.getLogger(MiguVideoConfigController.class);
	
	@Resource
	private IMiguVideoConfigService miguVideoConfigService;
	@Resource
    private IIpService ipService;
	@Resource
	private FileManager fileManager;
	

	/**
	 * 列表页面
	 * 
	 * @param model
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "list")
	public String showMiguVideoConfigList(Model model) throws Exception {
		return "/miguVideoConfig/miguVideoConfigList";
	}
	
	@RequestMapping(value = "getMiguVideoConfigListPage")
	@ResponseBody
	public Map<String, Object> getMiguVideoConfigListPage(DataGridModel page, MiguVideoConfigBean miguVideoConfig) throws Exception {
		String sname = miguVideoConfig.getSname();
		if (StringUtils.isNotBlank(sname)) {
			String[] snames = sname.split(" ");
			List<String> keywords = new ArrayList<>();
			for (String keyword : snames) {
				keywords.add(keyword);
			}
			miguVideoConfig.setKeywords(keywords);
		}
		return miguVideoConfigService.getMiguVideoConfigListPage(page, miguVideoConfig);
	}
	
	@RequestMapping(value = "/{id}/detail")
	public String getMiguVideoConfigDetail(@PathVariable Integer id, MiguVideoConfigBean miguVideoConfig, Model model) throws Exception {
		miguVideoConfig.setId(id);
		MiguVideoConfigBean result = miguVideoConfigService.getMiguVideoConfig(miguVideoConfig);
		model.addAttribute("mvc", result);
		return "/miguVideoConfig/miguVideoConfigDetail";
	}
	
	@RequestMapping(value = "/toAdd")
	public String toAdd() throws Exception {
		return "/miguVideoConfig/miguVideoConfigAdd";
	}
	
	@RequestMapping(value = "add", method = RequestMethod.POST)
	@ResponseBody
	public void add(MiguVideoConfigBean miguVideoConfig, @RequestParam MultipartFile file, HttpServletResponse response){
		String name = miguVideoConfig.getName();
		MiguVideoConfigBean queryMvc = new MiguVideoConfigBean();
		queryMvc.setName(name);
		MiguVideoConfigBean result  = miguVideoConfigService.getMiguVideoConfigByName(queryMvc);
		if (null != result) {
			ResponseUtils.responseInfoExists(response);
		} else {
			FileUploadVo fileVo = fileManager.uploadMiguVideoFile(file);
			Map<String, String> packInfo = fileVo.getPackageInfo();
			
			//渠道号不重复验证
			String channelId = packInfo.get("clientChanelId");
			MiguVideoConfigBean r  = miguVideoConfigService.getMiguVideoConfigByChannelId(channelId);
			if (null != r) {
				ResponseUtils.responseCustomMsg(response, "渠道号已存在");
			} else {
				miguVideoConfig.setChannelId(packInfo.get("clientChanelId"));
				miguVideoConfig.setVersion(packInfo.get("appVerion"));
				miguVideoConfig.setVersionCode(packInfo.get("appVersionCode"));
				miguVideoConfig.setSdkVersion("27fb3129-5a54-45bc-8af1-7dc8f1155501");
				miguVideoConfig.setLogSdkv("2.3.1");
				miguVideoConfig.setLogAc(packInfo.get("chanel"));
				miguVideoConfig.setLogApn("com.cmcc.cmvideo");
				miguVideoConfig.setLogAvc(packInfo.get("appTextVersion") +"|"+packInfo.get("appVersionCode"));
				miguVideoConfig.setLogAk("e0b8141eb04f4e46abf66fbd3e0a8ae3");
				miguVideoConfig.setLogAn("咪咕视频");
				miguVideoConfig.setLogSignVersion("2.3.1");
				miguVideoConfig.setReportSdkVersion(packInfo.get("logSDKVersion"));
				miguVideoConfig.setAppKey("01175D907A9707CC4BF0775D87C13356");
				miguVideoConfigService.add(miguVideoConfig);
				ResponseUtils.responseSuccess(response);
			}
		}
	}
	
	@RequestMapping(value = "/{id}/toUpdate")
	public String toUpdate(@PathVariable Integer id, MiguVideoConfigBean miguVideoConfig, Model model) throws Exception {
		miguVideoConfig.setId(id);
		MiguVideoConfigBean result = miguVideoConfigService.getMiguVideoConfig(miguVideoConfig);
		model.addAttribute("mvc", result);
		return "/miguVideoConfig/miguVideoConfigUpdate";
	}
	
	@RequestMapping(value = "update")
	@ResponseBody
	public void update(MiguVideoConfigBean miguVideoConfig, @RequestParam MultipartFile file, HttpServletResponse response){
		String name = miguVideoConfig.getName();
		Integer id = miguVideoConfig.getId();
		MiguVideoConfigBean result  = miguVideoConfigService.getMiguVideoConfigExName(name, id);
		if (null != result) {
			ResponseUtils.responseInfoExists(response);
		} else {
			if (file != null && !file.isEmpty()) {
				FileUploadVo fileVo = fileManager.uploadMiguVideoFile(file);
				Map<String, String> packInfo = fileVo.getPackageInfo();
				
				//渠道号不重复验证
				String channelId = packInfo.get("clientChanelId");
				MiguVideoConfigBean r  = miguVideoConfigService.getMiguVideoConfigByChannelId(channelId);
				if (null != r) {
					ResponseUtils.responseCustomMsg(response, "渠道号已存在");
				} else {
					miguVideoConfig.setChannelId(packInfo.get("clientChanelId"));
					miguVideoConfig.setVersion(packInfo.get("appVerion"));
					miguVideoConfig.setVersionCode(packInfo.get("appVersionCode"));
					miguVideoConfig.setSdkVersion("27fb3129-5a54-45bc-8af1-7dc8f1155501");
					miguVideoConfig.setLogSdkv("2.3.1");
					miguVideoConfig.setLogAc(packInfo.get("chanel"));
					miguVideoConfig.setLogApn("com.cmcc.cmvideo");
					miguVideoConfig.setLogAvc(packInfo.get("appTextVersion") +"|"+packInfo.get("appVersionCode"));
					miguVideoConfig.setLogAk("e0b8141eb04f4e46abf66fbd3e0a8ae3");
					miguVideoConfig.setLogAn("咪咕视频");
					miguVideoConfig.setLogSignVersion("2.3.1");
					miguVideoConfig.setReportSdkVersion(packInfo.get("logSDKVersion"));
					miguVideoConfig.setAppKey("01175D907A9707CC4BF0775D87C13356");
				}
			}
			
			miguVideoConfigService.update(miguVideoConfig);
			ResponseUtils.responseSuccess(response);;
		}
	}
	
	@RequestMapping(value = "delete")
	@ResponseBody
	public Map<String, Object> delete(MiguVideoConfigBean miguVideoConfig) throws Exception {
		miguVideoConfigService.delete(miguVideoConfig);
		return ResponseMapUtils.responseSuccess();
	}
	
	@RequestMapping(value = "updateMiguVideoStatus")
	@ResponseBody
	public Object updateMiguVideoStatus(MiguVideoConfigBean miguVideoConfig){
		if (miguVideoConfig.getId() == null||miguVideoConfig.getStatus()==null) {
			return ResponseMapUtils.responseFail("参数缺失，请确认参数再提交");
		}
		miguVideoConfigService.updateMiguVideoStatus(miguVideoConfig);
		return ResponseMapUtils.responseSuccess();
	}
	
	@RequestMapping(value = "/{id}/toCopy")
	public String toCopy(@PathVariable Integer id, MiguVideoConfigBean miguVideoConfig, Model model) throws Exception {
		miguVideoConfig.setId(id);
		MiguVideoConfigBean result = miguVideoConfigService.getMiguVideoConfig(miguVideoConfig);
		model.addAttribute("mvc", result);
		return "/miguVideoConfig/miguVideoConfigCopy";
	}
	
	@RequestMapping(value = "{id}/provinceList")
    public String provinceList(@PathVariable Integer id, Model model) {
        List<ProvinceInfo> provinceList = ipService.getProvinceInfoList();
        List<MiguVideoProvinceConfig> idProvinceList = miguVideoConfigService.getProvinceById(id);
        Set<Integer> provinceSet = new HashSet<>();
        if (idProvinceList != null && idProvinceList.size() > 0) {
            for (MiguVideoProvinceConfig info : idProvinceList) {
                provinceSet.add(info.getProvince());
            }
        }
        if (provinceList != null && provinceList.size() > 0) {
            Iterator<ProvinceInfo> itetator = provinceList.iterator();
            while (itetator.hasNext()) {
                ProvinceInfo province = itetator.next();
                Integer provinceId = province.getId();
                if (provinceSet.contains(provinceId)) {
                    province.setChecked(true);
                } else {
                    province.setChecked(false);
                }
                if(provinceId== -1){
                    province.setProvinceName("未知");
                }
            }
        }
        model.addAttribute("provinceList", provinceList);
        return "miguVideoConfig/addProvince";
    }
	
	@RequestMapping(value = "saveProvince", method = RequestMethod.POST)
    @SystemControllerLog(description = "省份保存")
    public void saveProvince(String id, String openProvince, HttpServletResponse response) {
        try {
        	miguVideoConfigService.updateProvinceById(id, openProvince);
            ResponseUtils.responseSuccess(response);
        } catch (Exception e) {
            LOGGER.error("保存省份出错！", e);
            ResponseUtils.responseFailure(response);
        }
    }
	
	@RequestMapping(value = "getMiguVideoConfigList")
	@ResponseBody
	public List<MiguVideoConfigBean> getMiguVideoConfigList(MiguVideoConfigBean miguVideoConfig) throws Exception {
		return miguVideoConfigService.getMiguVideoConfigList(miguVideoConfig);
	}
}
